package com.example.xmlfactory.parse.pull;

import android.util.Xml;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Serializer;
import com.example.xmlfactory.parse.Var;

import org.xmlpull.v1.XmlSerializer;

import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

/**
 * Created by huangbei on 2017/9/12.
 */

public class PullSerializer implements Serializer{

    @Override
    public String serialize(Object obj) {
        try {
            ClassMsg classMsg = new ClassMsg(obj);

            //创建文档
            XmlSerializer serializer = Xml.newSerializer(); //由android.util.Xml创建一个XmlSerializer实例
            StringWriter writer = new StringWriter();
            serializer.setOutput(writer);   //设置输出方向为writer
            serializer.startDocument("UTF-8", true);

            //组装节点
            serializer.startTag("",classMsg.getClassName());

            Map<String,Var> properties = classMsg.getProperties();
            Set<String> keys = properties.keySet();
            for(String key : keys){
                serializer.startTag("",key);
                serializer.text(properties.get(key).getValue().toString());
                serializer.endTag("",key);
            }

            serializer.endTag("",classMsg.getClassName());
            serializer.endDocument();

            return writer.toString();

        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
